package com.only.common.util;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author only
 * @date 2023/12/13
 * @description
 */
public class PathUtil {
    /**
     * 获取文件名字绝对路径（包括文件名）中的文件名字
     * @param absFileName
     * @return
     */
    public static String getName(String absFileName) {
        int index = absFileName.lastIndexOf("/");

        if (index == -1) {
            return absFileName;
        }

        return absFileName.substring(index + 1);
    }

    /**
     * 获取文件的目录
     * @param absFileName
     * @return
     */
    public static String getParent(String absFileName) {
        int index = absFileName.lastIndexOf("/");

        if (index == -1) {
            return absFileName;
        }

        return absFileName.substring(0, index + 1);
    }

    public static String add(String parent, String subPath) {
        return StrUtil.format(
            "{}/{}",
            StrUtil.removeSuffix(parent, "/"),
            StrUtil.removePrefix(subPath, "/")
        );
    }

    public static String adds(String parent, String ...subPaths) {
        if (subPaths.length == 0) {
            return parent;
        }

        List<String> elems = new ArrayList<>();
        for (String subPath : subPaths) {
            elems.add(StrUtil.removeSuffix(StrUtil.removePrefix(subPath, "/"), "/"));
        }

        String subPathsStr = ListAndStringConverter.listToString(elems, "/");
        return add(parent, subPathsStr);
    }
}
